package com.redBook.controller;

import com.redBook.constant.JwtClaimsConstant;
import com.redBook.constant.JwtHeaderConstant;
import com.redBook.constant.MessageConstant;
import com.redBook.context.BaseContext;
import com.redBook.dto.NoteCommentDTO;
import com.redBook.dto.UserLoginDTO;
import com.redBook.entity.NoteComment;
import com.redBook.entity.NoteDetail;
import com.redBook.entity.NoteInfo;
import com.redBook.entity.UserDetail;
import com.redBook.exception.NotFindUserException;
import com.redBook.result.PageResult;
import com.redBook.result.Result;
import com.redBook.service.UserService;
import com.redBook.utils.JwtUtil;
import com.redBook.vo.UserLoginVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/category")
    public Result category(){
        return Result.success(userService.getCategoryList());
    }

    @GetMapping("/categoryChild")
    public Result categoryChild(){
        return Result.success(userService.getCategoryChildList());
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("提交的信息: {}",userLoginDTO);
        if(userLoginDTO.getPhone() != null){
            UserLoginVO loginVO = userService.login(userLoginDTO);

            Map<String, Object> claims = new HashMap<>();
            claims.put("phone", userLoginDTO.getPhone());
            claims.put(JwtClaimsConstant.USER_ID,loginVO.getId());

            String token = JwtUtil.createJWT(
                    JwtClaimsConstant.USER_ID,
                    1000 * 60 * 60 * 24,
                    claims);
            loginVO.setToken(token);
            log.info(token);
            return Result.success(loginVO);
        }else{
            return Result.error(MessageConstant.PHONE_IS_NULL);
        }
    }

    @GetMapping("/notes")
    public PageResult<NoteInfo> notesPage(@RequestParam long startPage,
                                          @RequestParam long size){
        PageResult<NoteInfo> notePage = userService.findNotesByPage((startPage - 1) * size, size);
        log.info("notes -> {}",notePage);
        return notePage;
    }

    @PostMapping("/notesByUser")
    public PageResult<NoteInfo> noteByUser(@RequestParam long startPage,
                                           @RequestParam long size){
        Long userId = BaseContext.getCurrentId();
        PageResult<NoteInfo> notePage = userService.findNotesByPageAndUser((startPage - 1) * size, size,userId);
        log.info("notes -> {}",notePage);
        return notePage;
    }

    @PostMapping("/info")
    public Result<UserDetail> userInfo(HttpServletRequest request){
        String token = request.getHeader(JwtHeaderConstant.TOKEN_NAME);
        if(token != null){
            Claims claims = JwtUtil.parseJWT(JwtClaimsConstant.USER_ID, token);
            UserDetail userDetail = userService.findUserById(Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString()));
            log.info("user -> {}",userDetail);
            return Result.success(userDetail);
        }else{
            throw new NotFindUserException("未找到用户");
        }
    }

    @PutMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        log.info("fileSize -> {}",file.getSize() / (1024 * 1024) + "MB");
        log.info("fileOriginalFilename -> {}",file.getOriginalFilename());
        if (!file.isEmpty()) {
            try {
                String uploadPath = "E:\\uploadTest";

                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                Path filePath = Paths.get(uploadPath, file.getOriginalFilename());

                Files.write(filePath, file.getBytes());

                return Result.success();
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("文件上传失败");
            }
        } else {
            return Result.error("文件不能为空");
        }
    }

    @GetMapping("/noteDetail")
    public Result noteDetail(@RequestParam Long noteId){
        if(noteId == 0){
            NoteDetail noteDetail = new NoteDetail();
            log.info("noteId == 1 -> {}",noteDetail);
            return Result.success(noteDetail);
        }else{
            NoteDetail noteDetail = userService.noteDetail(noteId);
            if(noteDetail != null){
                return Result.success(noteDetail);
            }else{
                log.info("noteDetailColl -> {}",noteDetail);
                return Result.error("未找到");
            }
        }

    }

//    @PostMapping("/submitNote")
//    public Result submitNoteDetail(@RequestBody NoteDetail noteDetail) {
//        // 这里的参数名要和前端 FormData 中的键名对应
//
//        log.info("Received SubmitNote: {}",noteDetail);
//
//        // 处理 submitNote 对象和 fileList，例如保存到数据库或文件系统
//
//        return null;
//    }

    @PostMapping("/submitNote")
    public Result submitNote(
            @RequestParam("title") String title,
            @RequestParam("context") String context,
            @RequestParam("power") String power,
            @RequestParam("address") String address,
            @RequestParam("files") List<MultipartFile> files,
            @RequestParam("height") List<Long> height,
            @RequestParam("width") List<Long> width) {

//        String uploadPath = "E:\\uploadTest";
        String uploadPath = "E:\\Desktop\\md\\项目练习\\小红书\\redBook\\public\\images";
        Long uid = BaseContext.getCurrentId();
        List<String> pathList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

        files.forEach(file->{
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            log.info("fileWidth -> {}",file);
            String times = LocalDateTime.now().format(formatter);
            String fileNameAfter = uid+times+file.getOriginalFilename();

            Path filePath = Paths.get(uploadPath, fileNameAfter);

            try {
                Files.write(filePath, file.getBytes());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//            pathList.add(uploadPath+"\\"+fileNameAfter);
            pathList.add(fileNameAfter);
        });

        userService.addNote(pathList,uid,title,context,power,address,height,width);
            // Process note data
            log.info("Title: {}",title);
            log.info("Context: {}" ,context);
            log.info("Power: {}" ,power);
            log.info("Address: {}" ,address);
            log.info("file Name: {}" ,files.size());

        return Result.success();
    }

    @PostMapping("/submitComment")
    public Result submitComment(@RequestBody NoteCommentDTO noteCommentDTO){
        noteCommentDTO.setUid(BaseContext.getCurrentId());
        log.info("noteComment -> {}",noteCommentDTO);
        userService.submitComment(noteCommentDTO);
        return Result.success();
    }
}
